package uqbar.comm;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import uqbar.comm.AbstractPort;

import com.Ostermiller.util.CircularByteBuffer;

public class EchoPort extends AbstractPort {

	private CircularByteBuffer circularByteBuffer;
	private InputStream input;
	private OutputStream output;

	@Override
	public void close() {
		this.circularByteBuffer = null;
	}

	@Override
	public void open() {
		this.circularByteBuffer = new CircularByteBuffer();
		this.input = this.circularByteBuffer.getInputStream();
		this.output = this.decorate(this.circularByteBuffer.getOutputStream());
	}

	private OutputStream decorate(final OutputStream outputStream) {
		return new OutputStream() {
			@Override
			public void write(final int arg0) throws IOException {
				outputStream.write(arg0);
				EchoPort.this.notifyDataAvailable();
			}
		};
	}

	@Override
	public InputStream getInputStream() {
		return this.input;
	}

	@Override
	public OutputStream getOutputStream() {
		return this.output;
	}

}
